package com.zzxx.service.impl;

import com.github.pagehelper.PageHelper;
import com.zzxx.domain.Role;
import com.zzxx.domain.UserInfo;
import com.zzxx.mapper.RoleMapper;
import com.zzxx.mapper.UserInfoMapper;
import com.zzxx.service.UserInfoService;
import com.zzxx.utils.UUIDUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service("userInfoService")
public class UserInfoServiceImpl implements UserInfoService {
    @Autowired
    private UserInfoMapper userInfoMapper;
    @Autowired
    private RoleMapper roleMapper;
    @Autowired
    private BCryptPasswordEncoder encoder;

    @Override
    public List<UserInfo> findAll(int pageNum, int pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        return userInfoMapper.findAll();
    }

    @Override
    public UserInfo findByUid(String uid) {
        return userInfoMapper.findByUid(uid);
    }

    @Override
    public void insert(UserInfo userInfo) {
        userInfo.setId(UUIDUtils.uuid());
        userInfo.setPassword(encoder.encode(userInfo.getPassword()));
        userInfoMapper.insert(userInfo);
    }

    @Override
    public List<Role> findOtherRolesById(String id) {
        return roleMapper.findOtherRolesById(id);
    }

    @Override
    public void addRole(String[] ids, String userId) {
        for (String roleId : ids){
            roleMapper.addRole(roleId, userId);
        }
    }

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        // 1.通过数据库查询数据 UserInfo
        UserInfo userInfo = userInfoMapper.findByUsername(username);

        // 2.使用我们自己的UserInfo构造一个User对象
        User user = new User(userInfo.getUsername(),
                userInfo.getPassword(),
                getGrantedAuthorities(userInfo.getRoles()));
        return user;
    }

    private List<GrantedAuthority> getGrantedAuthorities(List<Role> roles){
        List<GrantedAuthority> list = new ArrayList<>();
        for (Role role:roles){
            list.add(new SimpleGrantedAuthority("ROLE_"+role.getRoleName()));
        }
        return list;
    }
}
